package com.zhang.hadoop.spring.facotry;

import com.zhang.hadoop.spring.annotation.WorkerAnnotation;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author zhang yufei
 * @date 2022/4/14 10:26 上午
 **/
@Component
public class WorkerFactory implements ApplicationContextAware {

    private Map<String, Object> workerMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanDefinitions = applicationContext.getBeansWithAnnotation(WorkerAnnotation.class);
        if (Objects.nonNull(beanDefinitions) && !beanDefinitions.isEmpty()) {
            for (Map.Entry<String, Object> beanObjectEntry : beanDefinitions.entrySet()) {
                Optional<WorkerAnnotation> annotation = Optional.of(AopUtils.getTargetClass(beanObjectEntry.getValue()).getAnnotation(WorkerAnnotation.class));
                if (annotation.isPresent()) {
                    String key = annotation.get().name();
                    if (workerMap.containsKey(key) == false) {
                        workerMap.put(key, beanObjectEntry.getValue());
                    }
                }
            }
        }
    }

    public Map<String, Object> getWorkerMap() {
        return workerMap;
    }
}
